package com.witmore.neutron.ai.web.apiv2.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.db.entity.AgentDO;
import com.witmore.neutron.ai.db.entity.AgentPublishConfigDO;
import com.witmore.neutron.ai.db.mapper.AgentMapper;
import com.witmore.neutron.ai.db.mapper.AgentPublishConfigMapper;
import com.witmore.neutron.ai.web.annotation.RequiresPermission;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RobotWebDetailResult;
import com.witmore.neutron.ai.web.enums.PublishTypeEnum;
import com.witmore.neutron.ai.web.filter.AgentLoginRequired;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * V2 聊天窗口相关接口
 * Author: 豆子高
 * Date: 2025/5/15 15:03
 */
@RestController
@RequestMapping("/v2/chat")
public class ChatControllerV2 {

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private AgentPublishConfigMapper agentPublishConfigMapper;

    /**
     * 聊天页面初始化
     */
    @RequiresPermission("chat:index")
    @AgentLoginRequired(value = "agentCode")
    @GetMapping("/{agentCode}")
    public ResponseResult<RobotWebDetailResult> index(
            @PathVariable("agentCode") String agentCode) {
        AgentDO agentDO = agentMapper.selectOne(new LambdaQueryWrapper<AgentDO>()
                .eq(AgentDO::getAgentCode, agentCode)
        );
        if (agentDO == null) {
            return ResponseResult.fail(1001, "机器人不存在");
        }
        // 服务发布状态
        AgentPublishConfigDO configDO = agentPublishConfigMapper.selectOne(new LambdaQueryWrapper<AgentPublishConfigDO>()
                .eq(AgentPublishConfigDO::getAgentId, agentDO.getId())
                .eq(AgentPublishConfigDO::getAgentCode, agentCode)
                .eq(AgentPublishConfigDO::getPublishType, PublishTypeEnum.WEB.getCode())
        );
        if (configDO == null) {
            return ResponseResult.fail(1001, "机器人发布信息异常");
        }
        // 未发布
        if (configDO.getPublishStatus() == 0) {
            return ResponseResult.fail(1001, "机器人未发布");
        }
        RobotWebDetailResult robotWebDetailResult = new RobotWebDetailResult();
        BeanUtils.copyProperties(agentDO, robotWebDetailResult);
        robotWebDetailResult.setAgentShowTitle(configDO.getAgentShowTitle());
        return ResponseResult.success(robotWebDetailResult);
    }

}
